package cn.edu.hhu.servlet.student;

import cn.edu.hhu.Bean.Student;
import cn.edu.hhu.service.Impl.StudentServiceImpl;
import cn.edu.hhu.service.StudentService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @anthor: lddd
 * @date: 2020/5/8 - 22:12
 * @description:
 **/
@WebServlet("/studentRegistServlet")
public class StudentRegistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        String pwd = request.getParameter("pwd");
        String repeat_pwd = request.getParameter("repeat_pwd");
        //2封装对象
        Student student = new Student();
        try {
            BeanUtils.populate(student, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //3用户名或密码不能为空
        if (student.getSid() == null || student.getSid().length() == 0 || student.getPwd() == null || student.getPwd().length() == 0) {
            request.setAttribute("regist_msg", "学号或密码不能为空！");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }
        //4密码和确认密码不一致
        if (repeat_pwd == null || repeat_pwd.length() == 0 || !pwd.equalsIgnoreCase(repeat_pwd)) {
            request.setAttribute("regist_msg", "注册失败，两次密码输入不一致！");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            return;
        }
        //3调用service完成注册
        StudentService studentService = new StudentServiceImpl();
        boolean flag = studentService.regist(student);
        //4响应结果
        if (flag) {
            //注册成功
            request.setAttribute("regist_msg", "注册成功！");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
        } else {
            //注册失败
            request.setAttribute("regist_msg", "注册失败,名单未导入或账号已注册！");
            System.out.println(request.getContextPath());
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
